<?php
/**
 * For a running Search Demo see: http://amazonecs.pixel-web.org
 */


error_reporting(E_ALL);
require_once('config/constant.php');
require_once(DAEMONE_HOME.'/config/amazon.php');
require_once(DAEMONE_HOME.'/lib/lib_database.php');
require_once(DAEMONE_HOME.'/lib/lib_rss_database.php');
require_once(DAEMONE_HOME.'/lib/lib_helper_function.php');

require_once(DAEMONE_HOME.'/lib/AmazonECS.class.php');
get_connection();
/* TODO :: move in seprate script.
// add amazon categories
$index = 1;
foreach ($searchIndices as $item)
{
	execute_query ("insert into categories (category_id, category_name, parent_category_id, meta_keywords, amz_category_name, amz_grabed_on, amz_grabbed_status) values ($index, '$item', 0, '$item', '$item', now(), 0 )");
	$index++;	
}
exit;
*/

$counter = 0;
$counter_limit = $config['rss']['item.process.total.limit'];
$break_process = FALSE;
while(true)
{
	if($counter > $counter_limit || $break_process == TRUE)
		break;
		
	// loop categories
	$category_result = get_categories('WHERE amz_grabbed_status = 0 and amz_category_name IS NOT NULL AND is_active = 1', ' ORDER BY amz_grabed_on DESC ', 'LIMIT '.$config['rss']['category.process.limit']);
	if($category_result === FALSE || mysql_num_rows($category_result) == 0) 
	{
		echo "No more categories to grab.\r\n";
		$break_process == TRUE;
		break;
	}

	// iterate rss feed items
	while (!$break_process && $row = mysql_fetch_assoc($category_result)) 
	{
		/* TODO :: might be usefull this section.
		// *** Stop product grabing process, if get stop signal. 
		if(get_rss_grab_full_article_signal() == 'STOP' || $counter > $counter_limit)
		{
			$break_process = TRUE;
			break;
		}
		*/
		$counter = $counter + 1;
		global $category_id, $category_name;
		$category_id = $row['category_id'];
		$category_name = $row['amz_category_name'];
		
		echo 'Processing Category : ', $category_name, "\r\n<br/>";
		// *** get products from amazon 
		try
		{
			// get a new object with your API Key and secret key. Lang is optional.
			// if you leave lang blank it will be US.
			$amazonEcs = new AmazonECS(AWS_API_KEY, AWS_API_SECRET_KEY, 'com', AWS_ASSOCIATE_TAG);

			// If you are at min version 1.3.3 you can enable the requestdelay.
			// This is usefull to get rid of the api requestlimit.
			// It depends on your current associate status and it is disabled by default.
			// $amazonEcs->requestDelay(true);

			// for the new version of the wsdl its required to provide a associate Tag
			// @see https://affiliate-program.amazon.com/gp/advertising/api/detail/api-changes.html?ie=UTF8&pf_rd_t=501&ref_=amb_link_83957571_2&pf_rd_m=ATVPDKIKX0DER&pf_rd_p=&pf_rd_s=assoc-center-1&pf_rd_r=&pf_rd_i=assoc-api-detail-2-v2
			// you can set it with the setter function or as the fourth paramameter of ther constructor above
			$amazonEcs->associateTag(AWS_ASSOCIATE_TAG);
			
			// loop 10 pages, as amazon allow to show only 10 pages.
			$isMorePages = true;
			$categoryItemCount = 0;
			
			$amazon_result = execute_query("select * from amazon_item_lookup where is_active = 1");

			if($amazon_result === FALSE) 
			{
				echo  mysql_error();
			}
			
			while($amazon_row = mysql_fetch_array($amazon_result, MYSQL_ASSOC))
			{
				
				for($i=1; $i<=10 && $isMorePages; $i++)
				{
					// changing the category .
					$response = $amazonEcs->category($category_name)->optionalParameters(array('MinimumPrice' =>$amazon_row['minimum_price'],'Condition' => $amazon_row['condition'],'Availability'=>'Available','ItemPage'=>$i,'MerchantId'=>'Amazon'))->responseGroup('ItemAttributes,Offers,EditorialReview,Images,Similarities')->search($amazon_row['search_text']);
					//print_r($response);exit;
					
					$isMorePages = (intval($response->Items->TotalResults) >= $i ? true : false);
					if(intval($response->Items->TotalResults) == 0)
						continue;
					if($response->Items->Request->IsValid == 'True')
					{
						if (!is_array($response->Items->Item))
						{
							$categoryItemCount ++;
							parseNprocessItem($response->Items->Item, $amazon_row['id']);
						}
						else
						{
							foreach($response->Items->Item as $item)
							{
								try 
								{	
									$categoryItemCount ++;
									// echo json_encode($item),"\r\n";
									if(!property_exists($item, 'ItemAttributes') || !property_exists($item->ItemAttributes, 'ListPrice'))
									{
										continue;
									}
									parseNprocessItem($item, $amazon_row['id']);
									
								} 
								catch(Exception $e)
								{
									echo json_encode($e),"\r\n<br/>";
								}
							}
							// NOTE : exit for debug only.
							// exit;
						}
					}
					else
					{
						print_r($response);
					}
				
					// print_r($response);exit;
					sleep(20);
				}
			}
		}
		catch(Exception $e)
		{
			echo json_encode($e),"\r\n<br/>";  
		}
		echo "Processed Category : $category_name Item Fetched : $categoryItemCount \r\n<br/>";
		// NOTE : exit for debug only.
		// exit;

		execute_query("update categories set amz_grabbed_status=1 where category_id=$category_id");
	}
}
echo "total categories grabbed $counter\r\n";
execute_query("update categories set amz_grabbed_status=0 where is_active=1");
exit;


